package com.dabai.sas.utils;


import android.content.Context;
import android.net.Uri;

import androidx.documentfile.provider.DocumentFile;

import java.io.IOException;
import java.io.InputStream;

public class UriUtils {


    Uri uri;
    Context context;

    public UriUtils(Context context, Uri uri) {
        this.context = context;
        this.uri = uri;
    }

    /**
     * Uri获取文件名
     *
     * @return
     */
    public String getFileName() {
        if (context == null || uri == null) return null;
        DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);
        if (documentFile == null) return null;
        return documentFile.getName();
    }

    /**
     * 通过URI读取文本的方法
     *
     * @return
     */
    public String readFileText() {

        String str = null;

        if (uri != null) {
            InputStream inputStream = null;
            try {
                // 获取 OutputStream
                inputStream = context.getContentResolver().openInputStream(uri);
                int byteCount = 0;
                byte[] bytes = new byte[inputStream.available()];
                inputStream.read(bytes);

                str = new String(bytes,"UTF-8");

            } catch (IOException e) {
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                }
            }
        }

        return str;
    }


}
